var express = require('express');
// 引入远程接口的调用方法
const usersApi = require("../api/users");
const { createToken } = require("tools-factory-tang/jwt");
// 创建了一个路由器
var router = express.Router();
const _ = require("lodash");


// 路由作用：和页面相关的操作
// 获取用户列表
router.get('/', async function (req, res, next) {
  // 获取浏览器发送的值type为GET，在query接收
  const { curPage, eachPage } = req.query;
  console.log(curPage, eachPage);
  const data = await usersApi.get({ curPage, eachPage });
  res.send(data)
});

router.get('/findOne/:_id', async function (req, res, next) {
  // params去做路径解析
  const { _id } = req.params;
  const data = await usersApi.findOne(_id);
  res.send(data)
});

//新增用户
router.post('/addUser', async function (req, res, next) {
  const { username, password, phone, site, order, cartsId, coupons } = req.body;
  const data = await usersApi.addUsers({ username, password, phone, site, order, cartsId, coupons });
  res.send(data)
});

// 删除用户
router.post("/removeUser", async function (req, res, next) {
  const { _id } = req.body;
  console.log(_id);
  const data = await usersApi.removeUsers({ _id });
  res.send({ status: true });
})

//修改用户
router.post("/updateUser", async function (req, res, next) {
  const { newData } = req.body;
  // console.log(newData);
  await usersApi.update(newData);
  res.send({ state: true });
});

//新增地址
router.post("/addSite", async function (req, res, next) {
  const { _id, site } = req.body;
  await usersApi.addSite({ _id, site });
  res.send({ state: true });
});

//修改地址
router.post("/updataSite", async function (req, res, next) {
  const { _id, site, index } = req.body;
  await usersApi.updataSite({ _id, site, index });
  res.send({ state: true });
});

//用户新增优惠卷
router.post("/addCoupon", async function (req, res, next) {
  const { _id, coupons } = req.body;
  await usersApi.addCoupon({ _id, coupons });
  res.send({ state: true });
});

// 删除优惠卷
router.post("/removeCoupon", async function (req, res, next) {
  const { _id,couponsId } = req.body;
  const data = await usersApi.removeCoupon({ _id,couponsId });
  res.send({ status: true });
})

//登录
router.post("/login", async function (req, res, next) {
  const { username, password } = req.body; //获取用户输入的用户名、密码(通过解构)
  const data = await usersApi.login({ username, password });
  if (data) {
    const token = createToken({ username });
    res.send({
      status: true,
      username: data.username,
      token,
    });
  } else {
    res.send({
      status: false,
    });
  }
});
//注册
router.post("/reg", async function (req, res, next) {
  const { username, password, site , phone , cartsId } = req.body;
  const data = await usersApi.reg({ username, password ,site , phone , cartsId });
  if (data) {
    res.send({
      status: true,
    });
  } else {
    res.send({
      status: false,
    });
  }
});

// 暴露接口
module.exports = router;
